import router from './router/index';
import pinia from './store';
import { useUserInfoStore } from './store/user';

const userInfoStore = useUserInfoStore(pinia)
const whiteList = [
  '/login',
  '/register',
  '/home',
  '/sort',
  '/recommend',
  '/search',
  '/'
]

router.beforeEach(async (to, from, next) => {
  // console.log(1111, to)
  const token = userInfoStore.token;
  if (token) {
    if (to.path === '/register' || to.path === '/login') {
      next('/')
    } else {
      // console.log(2222)
      const hasUser = !!userInfoStore.userName
      // console.log(hasUser)
      if (hasUser) {
        next()
      } else {
        try {
          await userInfoStore.getuserInfoAsync()
          next(to)
        } catch (error) {
          userInfoStore.reset()
          next(`/login?redirect=${to.path}`)

        }
      }


    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // console.log(whiteList.indexOf(to.path))
      next()
    } else {
      // console.log(1111)
      next(`/login?redirect=${to.path}`)
    }
  }
})